package ui.forms;

import base.*;
import com.sun.lwuit.Button;
import com.sun.lwuit.Command;
import com.sun.lwuit.Form;
import com.sun.lwuit.TextArea;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import db.*;
import java.util.Date;
import java.util.Vector;
import stub.*;
import ui.Progress;
import utils.DateUtils;

/**
 * Transfer data from the local db to server db
 *
 * @author Shayan
 */
public class TransferDataForm extends Form implements ActionListener {

    public Context parent;
    private Progress progress;
    private TextArea lblStatus;
    private Button btnStart;
    private Command cmdChangeServer;
    private Command cmdBack;

    public TransferDataForm(final Form parent) {
        progress = new Progress();
        lblStatus = new TextArea();
        lblStatus.setPreferredW(getPreferredW());
        lblStatus.setPreferredH(50);
        lblStatus.setEditable(false);
        lblStatus.setGrowByContent(true);
        lblStatus.getStyle().setBorder(null);
        lblStatus.getStyle().setBgImage(null);
        lblStatus.getStyle().setBgTransparency(0);
        lblStatus.getSelectedStyle().setBorder(null);
        lblStatus.getSelectedStyle().setBgImage(null);
        lblStatus.getSelectedStyle().setBgTransparency(0);

        btnStart = new Button("Start");

        btnStart.addActionListener(this);

        addComponent(progress);
        addComponent(lblStatus);
        addComponent(btnStart);

        cmdBack = new Command("Back") {

            public void actionPerformed(ActionEvent evt) {
                parent.showBack();
            }
        };
        this.addCommand(cmdBack);
        this.setBackCommand(cmdBack);

        cmdChangeServer = new Command("Change Server");
        addCommand(cmdChangeServer);

        this.addCommandListener(this);

        progress.setVisible(false);
        lblStatus.setText("Ready to transfer. Press Start.");
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == btnStart) {
            new BackgroundTask() {

                public void performTask() {
                    try {
                        progress.setVisible(true);
                        lblStatus.setText("Start syncronization...");
                        progress.setProgress(10);

                        progress.setProgress(35);

                        // Send intakes to server
                        IntakeServicesSoap_Stub intakeServices = new IntakeServicesSoap_Stub();

                        lblStatus.setText("Find last intake on server");
                        Date lastDate = intakeServices.getLastIntakeDate(Context.currentUser.getId());
                        progress.setProgress(63);

                        lblStatus.setText("Get intakes from local db");
                        Date endOfToday = DateUtils.getEndOfDay(new Date()); // dateutil ignores HH:mm:ss

                        Vector intakeObjects = IntakeManager.getIntakes(
                                Context.currentUser.getId(),
                                lastDate,
                                endOfToday);
                        ArrayOfIntake intakes = new ArrayOfIntake(intakeObjects);
                        progress.setProgress(65);

                        if (intakes.size() > 0) {
                            lblStatus.setText("Sending " + intakes.size() + " intake(s) to server");
                            intakeServices.persistIntakes(intakes);
                        }

                        progress.setProgress(90);
                        lblStatus.setText("Sending user information to server");
                        UserServicesSoap_Stub userServices = new UserServicesSoap_Stub();
                        // this will not change username and password
                        userServices.updateInformation(Context.currentUser);

                        progress.setProgress(95);
                        lblStatus.setText("Receiving user information from server");
                        User serverUser = userServices.getUserById(Context.currentUser.getId());
                        Context.currentUser.setPassword(serverUser.getPassword());
                        UserManager.persist(Context.currentUser);

                        progress.setProgress(100);
                        progress.setVisible(false);

                        lblStatus.setText("Transfer successful. " + intakes.size() + " intake(s) transferred");
                    } catch (Exception ex) {
                        progress.setProgress(100);
                        progress.setVisible(false);
                        ex.printStackTrace();
                        lblStatus.setText("Error:" + ex.toString() + ex.getMessage());
                    }
                    btnStart.setVisible(false);
                    repaint();
                }
            }.start();
        } else if (e.getSource() == cmdChangeServer) {
            ChangeServerForm form = new ChangeServerForm(TransferDataForm.this);
            form.show();
        }
    }
}
